import image from '@ohos.multimedia.image';
// import screenshot from '@ohos.screenshot';
import { screenshot } from '@kit.ArkUI';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
// import urlUtil from "../utils/urlUtil"
import { util } from '@kit.ArkTS';
import ImageRecogManager from "../ApiModel/ImageRecogManager"
import type UIAbilityContext from "@ohos.app.ability.UIAbility"
import PixelMap from "@ohos.multimedia.image"
let TAG = "_:[screenShot]"


export class ScreenShotManager {
  i1:ImageRecogManager = new ImageRecogManager()

  async pick() {
    let pickInfo = await screenshot.pick()
    console.log(TAG, "pickInfo.pickRect", pickInfo.pickRect)
    console.log(TAG, "pickInfo.pixelMap", pickInfo.pixelMap, pickInfo.pixelMap.getPixelBytesNumber)
    return pickInfo
  }

  async shot() {
    console.log(TAG, "shot() called")
    let screenshotOptions: screenshot.ScreenshotOptions = {
      "rotation": 0
    }
    try {
      let pixelMap: image.PixelMap = await screenshot.save(screenshotOptions);
      console.log(TAG, 'Succeeded in shooting screenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
      return pixelMap
    } catch (err) {
      console.log(TAG, 'Failed to save screenshot. Code: ' + JSON.stringify(err));
      return await screenshot.save(screenshotOptions);
    }
  }

  async store(path:string, pixelmap) {
    let TAG = "_:[image storing]"
    try {
      console.log(TAG, "entered, path", path)
      // let path=this.context?.filesDir + "/"+fileName
      console.log(TAG, "path", path)
      let packOpts: image.PackingOption = { format: "image/jpeg", quality: 90 }
      let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      console.log(TAG, "file opened", file.fd)
      const imagePackerApi: image.ImagePacker = image.createImagePacker();
      console.log(TAG, "imagePacker created", imagePackerApi)
      await imagePackerApi.packToFile(pixelmap, file.fd, packOpts)
      console.info(TAG, 'packToFile succeeded.');
    } catch (e) {
      console.error(TAG, 'packToFile failed.', e);
    }
  }


  async shotAndStore(path:string) {
    let TAG = "_:shotAndStore"
    console.log(TAG, "entered")
    let pix = await this.shot()
    console.log(TAG, "shot() finish", pix?.getPixelBytesNumber())
    await this.store(path, pix )
    return pix
  }
  // async pix2Base64(pixelMap) {
  //   let imgBuf = new ArrayBuffer(pixelMap.getPixelBytesNumber());
  //   await pixelMap.readPixelsToBuffer(imgBuf);
  //   let buf8 = new Uint8Array(imgBuf);
  //   console.log(TAG, 'Succeeded in writing arrayBuffer', imgBuf.byteLength, buf8.length);
  //   console.log(TAG, 'buf8=', buf8.slice(10000, 11000));
  //   let b64 = "";
  //   try {
  //     b64 = urlUtil.toBase64(buf8);
  //   } catch (e) {
  //     console.log(TAG, "base64 fail", JSON.stringify(e));
  //   }
  //   console.log(TAG, "base64 convert success", b64.length, b64.slice(100, 110))
  //   pixelMap.release();
  //   console.log(TAG, "pixelMap released")
  //   return b64
  // }

  async path2Base64(path): Promise<string> {
    let TAG = "_:Path2Base64"
    try {
      console.log(TAG, "entered")
      const fileBuffer = await this.readFileAsUint8Array(path);
      console.log(TAG, "fileBuffer read finish", fileBuffer.byteLength)
      const base64Helper = new util.Base64Helper();
      console.log(TAG, "base64Helper created", base64Helper)
      const base64String = base64Helper.encodeToStringSync(fileBuffer);
      console.log(TAG, "base64Helper encode to string", base64String.slice(0, 100))
      // let txt=await fs.open( path+ "/"+"RECtest.txt",fs.OpenMode.CREATE|fs.OpenMode.WRITE_ONLY)
      // await fs.write(txt.fd,base64String)
      // fs.close(txt.fd)
      return base64String;
    } catch (error) {
      console.error(TAG, "encode error", JSON.stringify(error));
      return ""
    }
  }

  async readFileAsUint8Array(filePath: string): Promise<Uint8Array> {
    let TAG = "_:readFileAsUint8Array"
    try {
      console.log(TAG, "entered")
      let file = await fs.open(filePath, fs.OpenMode.READ_ONLY)
      console.log(TAG, "file opened", file.fd)
      let arrayBuffer = new ArrayBuffer(3686500);
      console.log(TAG, "arrayBuffer created", arrayBuffer.byteLength)
      let code = await fs.read(file.fd, arrayBuffer);
      console.log(TAG, "data read finish with code", code, " and ByteLength", arrayBuffer.byteLength)
      return new Uint8Array(arrayBuffer.slice(0,code));
    } catch (e) {
      console.error(TAG, "readFileAsUint8Array fail",JSON.stringify(e))
      return new Uint8Array(1)
    }
  }

}